<template>
	<view class="bg-gray-100 w-full h-screen">
		<view class="bg-gray-200 p-2">
			<input class="m-2 bg-white p-2" type="text" v-model="code" placeholder="请输入家长身份证号" />
			<button class="m-2 bg-sky-500 text-white" @click="userLogin">登录</button>
		</view>
		<view class="bg-white p-1 mt-1 rounded-2xl">
			<view class="flex justify-between items-center pl-4 pr-4 pt-4 pb-3">
				<view class="flex">
					<image class="w-16 h-16" src="/static/images/default_user.png" mode="aspectFit"></image>
					<view class="flex flex-col justify-center">
						<text class="text-lg p-1">{{student.fullname}}</text>
						<text class="text-sm text-gray-400 p-1">{{student.idnumber}}</text>
					</view>
				</view>

				<view class="flex flex-col justify-center items-center" @click="changeStudent">
					<cover-image class="changeStudent" src="/static/images/change.png"></cover-image>
					<text class="text-sm">切换</text>
				</view>
			</view>

		</view>


		<view class="-translate-y-2 bg-white p-1 mt-1  rounded-t-2xl">
			<uni-section class="mb-10" type="line" title="家长操作">
				<view class="flex flex-col flex-wrap justify-between items-center p-3  text-center">
					<view class="flex flex-wrap justify-between items-center m-2  w-11_12 ">
						<view class="bg-color-01 w-36 text-base leading-8 p-1 flex items-center justify-center rounded"
							@click="toPage('/pages/parentInfo/parentInfo?isNew=false')">
							<image class="w-5 h-5 mr-1" src="/static/images/xueshengxinxi.png" mode="aspectFit"></image>
							完善家长信息
						</view>
						<view class="bg-color-01 w-36 text-base leading-8 p-1 flex items-center justify-center rounded"
							@click="toPage('/pages/studentInfo/studentInfo?isNew=false&studentId='+student.id)">
							<image class="w-5 h-5 mr-1" src="/static/images/zizhuzhengce.png" mode="aspectFit"></image>
							修改学生档案
						</view>
					</view>
					<button class="bg-gray-200 w-11_12 m-2 p-1" @click="readZhengce">
						资助政策{{msg}}</button>
					<button class="bg-color-02 text-white w-11_12 m-2 p-1" @click="createShenqing">

						我要申请</button>
				</view>

			</uni-section>
		</view>
		<view class="shenqingList bg-white p-1 mt-1">
			<uni-section class="mb-10" type="line" title="申请记录">
				<template v-slot:right>
					<view class="text-xs text-sky-500" @click="clear">清理申请缓存</view>
				</template>
				<u-list height="auto">
					<u-list-item v-for="(item, index) in shenqingList" :key="index">
						<u-cell :border="false" :label="format(item.createTime)" isLink
							@click="showShenqing(item.id,item.shenqingStatus!=2||(item.jieguofabu==1&&item.jieguo=='申请未通过'))"
							:name="item.id">
							<template v-slot:title>
								<view>
									<text class="u-cell-text pr-2">{{item.activity.activityName}}</text>
								</view>
							</template>
						</u-cell>
						<view class="flex flex-wrap border-b border-slate-200 pb-3"
							@click="showShenqing(item.id,item.shenqingStatus!=2||(item.jieguofabu==1&&item.jieguo=='申请未通过'))">
							<!-- 待提交状态 --><u-tag class="m-1" v-if="item.shenqingStatus==1"
								@click="showShenqing(item.id,true)" text="申请待提交" plain size="mini"
								type="warning"></u-tag>
							<!-- 被班主任驳回 --><u-tag class="m-1" v-if="item.shenqingStatus==3"
								@click="showShenqing(item.id,true)" text="被班主任驳回" plain size="mini"
								type="error"></u-tag>
							<!-- 申请待审批 --><u-tag class="m-1"
								v-if="item.shenqingStatus==2&&(item.jieguofabu==undefined||item.jieguofabu==0)"
								@click="showShenqing(item.id,false)" text="申请待审批" plain size="mini"
								type="warning"></u-tag>
							<!-- 申请已通过 -->
							<template v-if="item.shenqingStatus==2&&item.jieguofabu==1&&item.jieguo!='申请未通过'"
								v-for="(j,i) in item.jieguo.split(',')" :key="j">
								<u-tag class="m-1" @click="showShenqing(item.id,false)" :text="j" plain size="mini"
									type="success"></u-tag>
							</template>
							<!-- 申请未通过 --><u-tag v-if="item.shenqingStatus==2&&item.jieguofabu==1&&item.jieguo=='申请未通过'"
								@click="showShenqing(item.id,false)" :text="item.jieguo" plain size="mini"
								type="error"></u-tag>
						</view>
					</u-list-item>
				</u-list>
				<u-empty mode="list" v-show="shenqingList.length==0" iconColor="#DEDEDE" text="您未发起过申请" :iconSize="40">
				</u-empty>
			</uni-section>
		</view>
	</view>
	<uni-popup ref="alertDialog" type="dialog">
		<uni-popup-dialog type="warn" confirmText="确定" :showClose="false" title="警告"
			:content="alertContent"></uni-popup-dialog>
	</uni-popup>

</template>

<script>
	import {
		login,
		checkNewUser,
		queryDefaultStudent,
		loginTest
	} from '@/api/login.js'
	import dayjs from 'dayjs'
	import lodashFull from '@/uni_modules/iRainna-lodash/js_sdk/js/lodash.full.min.js'
	const {
		isNil
	} = lodashFull()

	dayjs.locale('zh-cn');
	export default {
		data() {
			return {
				code: '',
				zhengceReadAlready: false,
				shenqingAlready: false,
				allowShenqing: false,
				activity: {},
				returnIndex: false,
				shenqingList: [],
				msg: '',
				alertContent: '',
				student: {
					id: '',
					fullname: '',
					idnumber: ''
				}
			}
		},
		onShow() {
			console.log("sonShow方法执行...");
			if (this.returnIndex) {
				this.loadDefaultStudent()
			}
		},
		onLoad(option) {
			console.log("onLoad方法执行...");
			// this.userLoginTest()
			// return

			if (this.valideLogin()) {
				console.log('用户已登录...', uni.getStorageSync('token'));
				//已授权登录时，检测是否为新用户
				let that = this
				checkNewUser().then(res => {
					if (res.success && res.isNew) {
						that.toPage('/pages/parentInfo/parentInfo?isNew=true')
					} else {
						that.loadDefaultStudent()
					}
				})
			}
		},
		methods: {
			valideLogin() {
				return (!isNil(uni.getStorageSync('token'))) && uni.getStorageSync('token') != ''
			},
			clear() {
				let that = this
				uni.showModal({
					title: '警告',
					content: '确定要清除本地缓存吗？',
					success: function(res) {
						if (res.confirm) {
							that.removeFormCache()
							uni.showToast({
								title: '缓存已清除！'
							});
						}
					}
				})
			},
			setFormCache() {
				let data
				let storageInfo = uni.getStorageInfoSync()
				if (storageInfo.keys.includes("shenqingDataArr")) {
					data = JSON.parse(uni.getStorageSync('shenqingDataArr'))
				} else {
					data = new Object()
				}

				data[this.student.id] = this.formData
				uni.setStorageSync('shenqingDataArr', JSON.stringify(data))
			},
			hasFormCache(name) {
				let storageInfo = uni.getStorageInfoSync()
				if (storageInfo.keys.includes(name)) {
					let data = JSON.parse(uni.getStorageSync(name))
					return !isNil(data[this.student.id])
				} else {
					return false
				}
			},

			removeFormCache() {
				if (this.hasFormCache("shenqingDataArr")) {
					//清除申请
					let shenqingDataArr = JSON.parse(uni.getStorageSync("shenqingDataArr"))
					if (shenqingDataArr) {
						delete shenqingDataArr[this.student.id]
						uni.setStorageSync('shenqingDataArr', JSON.stringify(shenqingDataArr))
					}
				}
				if (this.hasFormCache("lianghuaDataArr")) {
					//清除量化标准
					let lianghuaDataArr = JSON.parse(uni.getStorageSync("lianghuaDataArr"))
					if (lianghuaDataArr) {
						delete lianghuaDataArr[this.student.id]
						uni.setStorageSync('lianghuaDataArr', JSON.stringify(lianghuaDataArr))
					}
				}
			},
			readZhengce() {
				if (this.activity == undefined || this.activity == null) {
					this.alertContent = '当前学生没有符合条件的资助活动!'
					this.$refs.alertDialog.open()
				} else {
					if (!this.zhengceReadAlready) {
						this.toPage('/pages/studentInfo/confirmStudentInfo?isNew=false&studentId=' + this.student.id)
					} else {
						this.toPage('/pages/zizhuzhengce/zizhuzhengce')
					}


				}
			},
			showShenqing(e, flag) {
				let shenqingId = e.name != undefined ? e.name : e
				console.log(flag);
				if (flag) {
					this.editShenqing(shenqingId)
				} else {
					this.toPage('/pages/shenqingView/shenqingView?shenqingId=' + shenqingId + '&studentId=' + this.student
						.id)
				}

			},
			changeStudent() {
				this.toPage('/pages/studentList/studentList')
			},
			toPage(url) {
				this.returnIndex = true
				uni.navigateTo({
					url: url
				})
			},
			format(time) {
				return dayjs(time).format('YYYY-MM-DD')
			},

			/**
			 * 获取路径中携带的参数
			 */
			getURLParams() {

				var url = window.location.search;
				var theRequest = new Object();
				if (url.indexOf("?") != -1) {
					var str = url.substr(1);
					var strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
					}
				}

				return theRequest

			},
			/**
			 * 登录服务器（测试环境）
			 */
			userLoginTest() {
				console.log('正在登录服务器（测试环境）...');
				//html测试
				let that = this
				login({
					code: "test_code"
				}).then((res2) => {
					console.log('登陆成功，该用户为' + res2.isNew ? '【新用户】' : '【老用户】');
					uni.setStorageSync('token', res2.token)
					if (res2.isNew) {
						that.toPage('/pages/parentInfo/parentInfo?isNew=true')
					} else {
						this.loadDefaultStudent()
					}
				})
				uni.getStorageInfo({
					success: (res) => {
						console.log("getStorageInfo", res);
					}
				})
			},

			/**
			 * 服务器登录
			 */
			userLogin() {
				console.log('正在登录服务器...');
				//如果存在微信授权code，直接登录服务器
				loginTest({
					code: this.code
				}).then((res2) => {
					if (res2.success) {
						uni.setStorageSync('token', res2.token)
						if (res2.isNew) {
							uni.redirectTo({
								url: '/pages/parentInfo/parentInfo?isNew=true'
							});
						} else {
							this.loadDefaultStudent()
						}
					} else {
						uni.showToast({
							icon: "fail",
							title: res.msg
						});
					}

				})


			},

			/**
			 * 获取微信授权code
			 */
			authorizeRequest() {
				let ctx = encodeURIComponent('http://xszz.jinedu.cn')
				let wx_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxeb98dc2a7daec47f&redirect_uri=' +
					ctx + '&response_type=code&scope=snsapi_userinfo#wechat_redirect'
				window.location.href = wx_url
			},

			/**
			 * 创建申请
			 */
			createShenqing() {
				let that = this
				if (this.activity == undefined || this.activity == null) {
					this.alertContent = '当前学生没有符合条件的资助活动!'
					this.$refs.alertDialog.open()
				} else if (!this.zhengceReadAlready) {
					this.alertContent = '必须先阅读政策,才能能发起申请!'
					this.$refs.alertDialog.open()
				} else if (!this.allowShenqing) {
					this.alertContent = '您已放弃申请!'
					this.$refs.alertDialog.open()
				} else if (this.shenqingAlready) {
					this.alertContent = '该学生已发起申请，无法创建新的申请!'
					this.$refs.alertDialog.open()
				} else {
					queryDefaultStudent().then(res3 => {
						if (res3.success) {
							this.student = res3.student;
							this.zhengceReadAlready = res3.zhengceReadAlready
							this.shenqingAlready = res3.shenqingAlready
							this.allowShenqing = res3.allowShenqing
							this.activity = res3.activity
							this.shenqingList = res3.shenqingList
							if (res3.student != undefined) {
								getApp().globalData.studentId = res3.student.id
							}
							if (res3.activity != undefined) {
								getApp().globalData.activityId = res3.activity.id
							}
							this.toPage('/pages/shenqingForm/shenqingForm?studentId=' + this.student.id)
						} else {
							uni.showModal({
								title: '提示',
								content: res3.msg,
								showCancel: false,
								confirmText: '去绑定',
								success: function(res) {
									if (res.confirm) {
										that.toPage('/pages/studentList/studentList')
									}

								}
							});
						}
					})
					this.toPage('/pages/shenqingForm/shenqingForm?studentId=' + this.student.id)
				}

			},
			/**
			 * 编辑申请
			 */
			editShenqing(shenqingId) {
				let that = this
				if (this.activity == undefined || this.activity == null) {
					this.alertContent = '当前学生没有符合条件的资助活动!'
					this.$refs.alertDialog.open()
				} else if (!this.zhengceReadAlready) {
					this.alertContent = '必须先阅读政策,才能能发起申请!'
					this.$refs.alertDialog.open()
				} else if (!this.allowShenqing) {
					this.alertContent = '您已放弃申请!'
					this.$refs.alertDialog.open()
				} else {
					queryDefaultStudent().then(res3 => {
						if (res3.success) {
							this.student = res3.student;
							this.zhengceReadAlready = res3.zhengceReadAlready
							this.shenqingAlready = res3.shenqingAlready
							this.allowShenqing = res3.allowShenqing
							this.activity = res3.activity
							this.shenqingList = res3.shenqingList
							if (res3.student != undefined) {
								getApp().globalData.studentId = res3.student.id
							}
							if (res3.activity != undefined) {
								getApp().globalData.activityId = res3.activity.id
							}
							this.toPage('/pages/shenqingForm/shenqingForm?studentId=' + this.student.id +
								'&shenqingId=' + shenqingId)
						} else {
							uni.showModal({
								title: '提示',
								content: res3.msg,
								showCancel: false,
								confirmText: '去绑定',
								success: function(res) {
									if (res.confirm) {
										that.toPage('/pages/studentList/studentList')
									}

								}
							});
						}
					})

				}
			},
			/**
			 * 加载默认学生
			 */
			async loadDefaultStudent() {
				this.returnIndex = false
				let that = this
				//校验是否已登陆
				if (this.valideLogin()) {
					let res3 = await queryDefaultStudent()

					if (res3.success) {
						this.student = res3.student;
						this.zhengceReadAlready = res3.zhengceReadAlready
						this.shenqingAlready = res3.shenqingAlready
						this.allowShenqing = res3.allowShenqing
						this.activity = res3.activity
						this.shenqingList = res3.shenqingList
						if (res3.student != undefined) {
							getApp().globalData.studentId = res3.student.id
						}
						if (res3.activity != undefined) {
							getApp().globalData.activityId = res3.activity.id
						}

					} else {
						uni.showModal({
							title: '提示',
							content: res3.msg,
							showCancel: false,
							confirmText: '去绑定',
							success: function(res) {
								if (res.confirm) {
									that.toPage('/pages/studentList/studentList')
								}

							}
						});
					}
				}

			},

		}
	}
</script>

<style>
	.changeStudent {
		width: 30rpx;
		height: 30rpx;
	}

	@font-face {
		font-family: CustomFont;
		src: url('/static/iconfont.ttf');
	}

	.-translate-y-4 {
		transform: translateY(-1rem);
	}

	.-translate-y-2 {
		transform: translateY(-0.5rem);
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.shenqingList {
		min-height: 540rpx;
	}

	.student {
		height: 300rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.nav-title {
		font-size: 40rpx;
		width: 100%;
		text-align: center;
	}

	.nav {
		height: 360rpx;
	}

	.bg_01 {
		background-image: url("/static/images/bg_01.png");
		background-repeat: no-repeat;
		background-size: 100% auto;
	}

	.bg-color-01 {
		background-color: #E6F2FF;
	}

	.leading-12 {
		line-height: 3;
	}

	.bg-color-02 {
		background-image: linear-gradient(to bottom, #38b0e8, #328bde);
	}
</style>